package com.epoint.netty.chat.handler;

import com.epoint.netty.chat.message.GroupCreateRequestMessage;
import com.epoint.netty.chat.message.GroupCreateResponseMessage;
import com.epoint.netty.chat.server.session.Group;
import com.epoint.netty.chat.server.session.GroupSession;
import com.epoint.netty.chat.server.session.GroupSessionFactory;
import com.epoint.netty.chat.server.session.GroupSessionMemoryImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Set;

public class GroupCreateRequestHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, GroupCreateRequestMessage groupCreateRequestMessage) throws Exception {
        // 群名
        String groupName = groupCreateRequestMessage.getGroupName();

        // 群成员
        Set<String> members = groupCreateRequestMessage.getMembers();

        GroupSession groupSessionMemory = GroupSessionFactory.getGroupSession();

        Group group = groupSessionMemory.createGroup(groupName, members);
        // 则第一次创建
        if(group == null){
            GroupCreateResponseMessage groupCreateResponseMessage = new GroupCreateResponseMessage(true, "创建成功");
            channelHandlerContext.channel().writeAndFlush(groupCreateResponseMessage);
        }
        else{
            GroupCreateResponseMessage groupCreateResponseMessage = new GroupCreateResponseMessage(false, "创建失败");
            channelHandlerContext.channel().writeAndFlush(groupCreateResponseMessage);
        }

    }
}
